var chkd_pro=[],page_ched_pro=[];//chkd_pro 当前页面选择的，page_ched_pro 当前页面已选择的
var areas=[];
$(function () {

    $('#valid_begin_time').daterangepicker({
        "singleDatePicker": true,
        "timePicker": true,
        "timePicker24Hour": true,
        "timePickerSeconds": true,
        "parentEl": "200",

        locale: {
            format:'YYYY-MM-DD HH:mm:ss',
            applyLabel: '确认',
            cancelLabel: '取消',
            weekLabel: 'W',
            customRangeLabel: 'Custom Range',
            daysOfWeek:["日","一","二","三","四","五","六"],
            monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]
        }
    }, function(start, end, label) {
        $('#valid_begin_time').val(start.format('YYYY-MM-DD HH:mm:ss'));
    });


    $('#valid_end_time').daterangepicker({
        "singleDatePicker": true,
        "timePicker": true,
        "timePicker24Hour": true,
        "timePickerSeconds": true,
        "parentEl": "200",
        locale: {
            format:'YYYY-MM-DD HH:mm:ss',
            applyLabel: '确认',
            cancelLabel: '取消',
            weekLabel: 'W',
            customRangeLabel: 'Custom Range',
            daysOfWeek:["日","一","二","三","四","五","六"],
            monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]
        }
    }, function(start, end, label) {
        $('#valid_end_time').val(start.format('YYYY-MM-DD HH:mm:ss'));
    });
    //取消创建
    $("#btn_cancel").click(function(){
        window.location.href="/salemanPayrule/list";
    })

    //保存创建
    $("#btn_save").click(function () {
        var form = window.form_new_payrule;
        var name = form.name.value;
        var payway = form.payway.value;
        var day_limit = form.day_limit.value;
        var pay_condition = form.pay_condition.value;
        var pay_limit;


        var begin_time = $("#valid_begin_time").val();
        var end_time =$("#valid_end_time").val();
        if(begin_time=="" || end_time==""){
            bootbox.balert("请选择有效时间!");
            return false;
        }
        var valid_begin_time = new Date(begin_time.replace(new RegExp("-","gm"),"/")).getTime();
        var valid_end_time = new Date(end_time.replace(new RegExp("-","gm"),"/")).getTime();

        if(valid_end_time <= valid_begin_time){
            bootbox.balert("有效时间结束时间不能小于等于开始时间!");
            return false;
        }
        if(!name){
            bootbox.balert("规则名称必须填写!");
            return;
        }
        if(!day_limit){ //数字（验证） todo
            bootbox.balert("每日提现次数必须填写!");
            return;
        }

        if(!pay_condition){
            if(!pay_limit){
                bootbox.balert("请选择提现条件并填写!");
                return;
            }
        }

        if(pay_condition == 1){
            pay_limit = $("#by_bing").val();
            if(!pay_limit){
                bootbox.balert("请选择提现条件并填写!");
                return;
            }
        }else if(pay_condition == 2){
            pay_limit = $("#by_price").val();
            if(!pay_limit){
                bootbox.balert("请选择提现条件并填写!");
                return;
            }
        }


        //验证产品选择
        if(chkd_pro.length <= 0){
            bootbox.balert("请选择产品 !");
            return;
        }

        var proList=[];
        for(var i=0; i<chkd_pro.length; i++) {
            var id=chkd_pro[i];
            var pro = {proId:id, proName:$("#pro_name_" + id).text(), price:$("#pro_price_"+id).text()}
            proList.push(pro);
        }
       if(!getAreas()){
           return ;
       }
        var payrule = {name: name, valid_begin_time:valid_begin_time, valid_end_time:valid_end_time, payway:payway,
            day_limit:day_limit,pay_limit:pay_limit, pay_condition:pay_condition, pros:proList,area:areas};
        $.postJsonBody("/salemanPayrule/add_submit", payrule, function (re) {
            window.location.href="/salemanPayrule/list";
        })
    });

    //编辑创建
    $("#btn_edit_save").click(function () {
        var form = window.form_new_payrule;
        var name = form.name.value;
        var payruleId = $("#hidden_id").val();
        var payway = form.payway.value;
        var day_limit = form.day_limit.value;
        var pay_condition = form.pay_condition.value;
        var pay_limit;

        var begin_time = $("#valid_begin_time").val();
        var end_time =$("#valid_end_time").val();
        if(begin_time=="" || end_time==""){
            bootbox.balert("请选择有效时间!");
            return false;
        }
        var valid_begin_time = new Date(begin_time.replace(new RegExp("-","gm"),"/")).getTime();
        var valid_end_time = new Date(end_time.replace(new RegExp("-","gm"),"/")).getTime();
        if(valid_end_time <= valid_begin_time){
            bootbox.balert("有效时间结束时间不能小于等于开始时间!");
            return false;
        }
        if(!name){
            bootbox.balert("规则名称必须填写!");
            return;
        }
        if(!day_limit){ //数字（验证） todo
            bootbox.balert("每日提现次数必须填写!");
            return;
        }
        if(!pay_condition){
            if(!pay_limit){
                bootbox.balert("请选择提现条件并填写!");
                return;
            }
        }

        if(pay_condition == 1){
            pay_limit = $("#by_bing").val();
            if(!pay_limit){
                bootbox.balert("请选择提现条件并填写!");
                return;
            }
        }else if(pay_condition == 2){
            pay_limit = $("#by_price").val();
            if(!pay_limit){
                bootbox.balert("请选择提现条件并填写!");
                return;
            }
        }
        //验证产品选择
        if(chkd_pro.length <= 0){
            bootbox.balert("请选择产品 !");
            return;
        }

        var proList=[];
        for(var i=0; i<chkd_pro.length; i++) {
            var id=chkd_pro[i];
            var pro = {proId:id, proName:$("#pro_name_" + id).text(), price:$("#pro_price_"+id).text()}
            proList.push(pro);
        }
        var boolean = getAreas();
        if(!boolean){
            return false;
        }
        var payrule = {id:payruleId,name: name, valid_begin_time:valid_begin_time, valid_end_time:valid_end_time, payway:payway,
            day_limit:day_limit,pay_limit:pay_limit, pay_condition:pay_condition, pros:proList,area:areas};
        $.postJsonBody("/salemanPayrule/edit_submit", payrule, function (re) {
            window.location.href="/salemanPayrule/list";
        })
    });

    /******************** 编辑 添加区别 **********************************/
    if($("#hidden_id").val() != '' && $("#hidden_id").val() != undefined){

        $("#product_table tr").each(function(){
            chkd_pro.push( $(this).data("id") +"")
        });
    }else{
        $('#valid_end_time').val("");
        $('#valid_begin_time').val("");
    }

    /******************** 区域 **********************************/
    //触发省市县插件
    $(".area").click(function (e) {
        SelCity(this,$(this),e);
    });
    $("#btn_add_area").click(function(e){
        var new_div=$("#add_area_div").clone(true);
        // var num = $("[class=area_div]").length;
        new_div.attr("id","" );
        new_div.removeClass("hide");
        new_div.addClass("area_div");

        new_div.insertAfter("#regionDiv");
    });

    $(".btn_delete_area").on("click", function(){
        $(this).parents(".area_div").remove();
    });


    function  getAreas(){
        areas=[];
        var code=[],city=[],province=[];
        var bool =true;
        $(".area_div").each(function(){
            var adname = $(this).find(".area").val();
            var adcode=$(this).find(".adcode").val();
            if(adcode == undefined){
                bootbox.balert("请完成区域选择 !");
                bool= false;
                return;
            }
            var type=$(this).find(".adcode").attr("data-type");
            var advalue=$(this).find(".adcode").attr("data-code")
            var codeStr=advalue.split("-");
            if(adname == '' || adcode == "" || adcode==undefined){
                bootbox.balert("请完成区域选择 !");
                bool= false;
                return;
            }
            if(province.indexOf(adcode) !=-1){
                bootbox.balert("请检查您的适用区域，存在重复 !");
                bool= false;
                return;
            }else if(city.indexOf(adcode) !=-1){
                bootbox.balert("请检查您的适用区域，存在重复 !");
                bool= false;
                return;
            }
            for(var i =0;i<codeStr.length;i++){
                if(i==0){
                    province.push(codeStr[i]);
                }
                if(i==1){
                    city.push(codeStr[i]);
                }
                if(code.indexOf(codeStr[i]) != -1){
                    bootbox.balert("请检查您的适用区域，存在重复 !");
                    bool= false;
                    return;
                    break;
                }
            }

            var area={adname:adname,adcode:adcode,adlevel:type,advalue:advalue};
            areas.push(area);
            code.push(adcode);
        });
        return bool;
    }


    /***********选择商品页面 选择商品相关操作 start*********************/
    //取消商品选择
    $("#selectPro_cancel").click(function(){
        $("[name='selectedProduct']").hide();
    });
    //选择完商品，确认
    // var oldInnerHTML = $("#product_table").html();
    $("#selectPro_confirm").click(function(){
        //获取选中的记录id,根据id查询出列表，展示
        var chk_value =[];
        $('input[name="product"]:checked').each(function(){
            chk_value.push($(this).val());
        });

        if(chk_value.length == 0){
            bootbox.balert("没有选中任何商品!");
            return;
        }else{
            var str = "";
            for(var i= 0; i<chk_value.length; i++){
                var id = chk_value[i];
                if($("#price_" +id).val() == null || $("#price_" +id).val() ==''){
                    bootbox.balert("ID为【"+id+"】的商品没有价格，请填写 !");
                    return;
                }
            }
            for(var i= 0; i<chk_value.length; i++){
                var id = chk_value[i];

                if(chkd_pro.indexOf(id) == -1){
                    chkd_pro.push(id);
                }else{
                    $("#pro_tr_" + id).remove();
                }
                str += '<tr id="pro_tr_'+id+'" data-id="'+id+'">' +
                    '<td >'+chk_value[i] + '</td>'+
                    '<td id="pro_name_'+id+'">'+ $(".name_" +id).text() + '</td>' +
                    '<td>'+ $(".number_" +id).text() + '</td>' +
                    '<td id="pro_price_'+id+'">'+ $("#price_" +id).val() + '</td>' +
                    '<td><button type="button" class="btn btn-default btn-xs delete-btn" data-id="'+id+'" >删除</button></td>'+
                    '</tr>';

            };
            var len = page_ched_pro.length;
            if(len>0){
                for(var i=0;i<len;i++){
                    if(chk_value.indexOf(page_ched_pro[i]) == -1){
                        $('#pro_tr_'+page_ched_pro[i]).remove();
                        for(var j=0; j<chkd_pro.length; j++) {
                            if (chkd_pro[j] == page_ched_pro[i]) {
                                chkd_pro.splice(j, 1);
                                break;
                            }
                        }
                    }
                }
            }
            $('#product_table').append(str);
            //关闭商品选择页面，
            $("[name='selectedProduct']").hide();
        }
    });

    //选择完商品,点击删除按钮操作
    $("#product_table").on("click",".delete-btn", function(){
        var $this =$(this), id=$this.data("id");
        for(var i=0; i<chkd_pro.length; i++) {
            if(chkd_pro[i] == id) {
                chkd_pro.splice(i, 1);
                break;
            }
        }
        //修改产品框显示
        // $("#product_"+ id).prop("checked", false);
        // $("#price" + id).val("");
        $this.parent().parent().remove();
    });

    //产品弹出框 点击结果
    $('#selectedProduct_modals').on('show.bs.modal', function (event) {

        page_ched_pro=[];
        $('input[name="product"]').prop("checked", false);
        $(".price").val("");
        $('input[name="product"]').each(function(){
            var proId = $(this).val();
            if(chkd_pro.indexOf(proId) != -1){
                page_ched_pro.push(proId);
                $("#product_"+ proId).prop("checked", true);
                $("#price_" + proId).val($("#pro_price_"+proId).text());
            }
        });
    });

    /**
     * 加载产品数据
     * @param page
     * @param state 值为1 时 代表的是点击查询
     */
    function resetData(page,state){
        var keyword = $('#keyword').val();

        page = page || 1;
        var  url ="/lgsBills/getProductList?keyword=" + keyword + "&page=" +page;

        $.post(url, function (re) {
            var result = re.data, resultList=result.result;

            var str = "", thisPro =[];
            page_ched_pro=[];
            for(var i=0; i<resultList.length; i++){

                var id = resultList[i].id;
                thisPro.push(id+"");

                str += '<tr>' +
                    '<td><input type="checkbox" name="product" value="'+id+'" id="product_'+id+'" /></td>'+
                    '<td>'+ id + '</td>'+
                    '<td class="name_'+id+ '">'+ resultList[i].name + '</td>' +
                    '<td class="number_'+id+ '">'+ resultList[i].number + '</td>' +
                    '<td><input type="text" class="price" id="price_'+id+'"  data-id="'+id+'"  size="5"/></td>';
            }
            $('#product_model').html(str);
            resetPage(result.pageTotal, page);
            $("#proTotal").text(result.resultTotal);

            //页面回显已经选中的产品
            for(var i=0;i<chkd_pro.length;i++){
                if(thisPro.indexOf(chkd_pro[i]) != -1){
                    var proId = chkd_pro[i];
                    page_ched_pro.push(proId);
                    $("#product_"+ proId).prop("checked", true);
                    $("#price_" + proId).val($("#pro_price_"+proId).text());
                }
            }
        });
    }


    function resetPage(totalPage, currPage){
        var innerHTML = [];
        currPage = currPage || 1;
        innerHTML.push('<ul class="pagination pagination-sm no-margin">');
        if(currPage > 1){
            innerHTML.push('<li class="prev"><a href="javascript:;"><span>上一页</span></a></li><li><a href="javascript:;"><span>1</span></a></li>');
        }
        if(currPage - 4 > 1){
            innerHTML.push('<li class="bigPrev"><a href="javascript:;"><span>...</span></a></li>')
        }
        for(var i = currPage - 3; i < currPage; i++){
            if(i > 1){
                innerHTML.push('<li><a href="javascript:;"><span>',i,'</span></a></li>');
            }
        }
        innerHTML.push('<li class="active"><span>', currPage,'</span></li>')
        for(var i = currPage+1; i < currPage+3; i++){
            if(i < totalPage){
                innerHTML.push('<li><a href="javascript:;"><span>',i,'</span></a></li>');
            }
        }
        if(currPage < totalPage - 3){
            innerHTML.push('<li class="bigNext"><a href="javascript:;"><span>...</span></a></li>');
        }
        if(currPage < totalPage){
            innerHTML.push('<li><a href="javascript:;"><span>', totalPage,'</span></a></li>',
                '<li class="next"><a href="javascript:;"><span>下一页</span></a></li>');
        }
        innerHTML.push("</ul>")
        $("#page_model").data("total", totalPage).html(innerHTML.join(""));
    }

    resetPage(parseInt($("#page_model").data("total")));

    $("[name='pro_query']").click(function () {
        resetData(1,1);
    });

    $("#page_model").on("click", "li", function () {
        if($(this).hasClass("active")){
            return false;
        }
        var currPage = parseInt($("#page_model .active").text()),
            totalPage = $("#page_model").data("total");
        if($(this).hasClass("prev")){
            currPage--;
        } else if($(this).hasClass("next")){
            currPage++;
        } else if($(this).hasClass("bigPrev")){
            currPage -= 5;

            if(currPage < 1){
                currPage = 1;
            }
        } else if($(this).hasClass("bigNext")){
            currPage += 5;

            if(totalPage - currPage < 0){
                currPage = totalPage;
            }
        } else {
            currPage = parseInt($(this).text());
        }

        resetData(currPage);
    });
    /***********选择商品页面 选择商品相关操作 end***********************/
});